<template>
  <div class="comput-result">
    <div class="result-box">
      <div class="tabs-box" v-show="showTabs">
        <div class="tabs-title">
          <span>控制断面名称</span>
        </div>
        <div class="tabs-list">
          <div
            :class="['list-item', currentIndex == index ? 'active' : '']"
            v-for="(item, index) in sectionArr"
            :key="index"
            @click="handleClickTabs(item, index)"
          >
            <el-tooltip :content="item.blknm" placement="top" :disabled="item.blknm.length < 6">
              <span>{{ item.blknm }}</span>
            </el-tooltip>
          </div>
        </div>
      </div>
      <div class="box-right">
        <div class="comput-times">
          <div class="times-title">
            <span class="font-blue">计算场次：</span>

            <el-button type="primary" class="add-count" @click="handleAddCount">新建场次</el-button>
            <el-button type="primary" class="comput" @click="handleComputed">计算</el-button>
            <el-button
              v-if="props.showEcharts"
              type="info"
              class="btn-plus"
              @click="handleAmplify"
              link
            >
              <el-icon>
                <FullScreen />
              </el-icon>
            </el-button>
            <!-- 测试地图弹框 最后删掉 -->
            <!-- <el-button type="primary" @click="showMapInfo">测试map</el-button>
            <el-button type="primary" @click="showMapbasin">流域信息弹框</el-button>
            <el-button type="primary" @click="showMapRiver">河道信息弹框</el-button>
            <el-button type="primary" @click="showMapNode">节点信息弹框</el-button> -->
          </div>
          <div class="times-list" v-if="props.ccInfo.length > 0">
            <div
              :class="['times-item', currentTime == index ? 'active' : '']"
              :key="index"
              v-for="(item, index) in props.ccInfo"
              @click="handleClickTime(item, index)"
            >
              <span>{{ item.ccName }}</span>
              <span class="close-icon" @click="handleClickDelete(item)">X</span>
            </div>
          </div>
          <div class="times-list times-center" v-else>
            <span>暂无...</span>
          </div>
          <!-- <div class="times-list" v-else>
            <div
              :class="['times-item', currentTime == index ? 'active' : '']"
              :key="index"
              v-for="(item, index) in ccInfos"
              @click="handleClickTime(item, index)"
            >
              <span>{{ item.code }}</span>
            </div>
          </div>-->
        </div>
        <div class="switch-box">
          <div class="comput-result-box">
            <div class="box-title">
              <span class="font-blue">各场次计算结果：</span>
            </div>
            <div class="box-form">
              <div class="form-item">
                <div class="item-title">
                  <span class="title-left">场次名称:</span>
                  <span>{{ calcResult.info.ccCode }}</span>
                </div>
                <div class="item-title">
                  <span class="title-left">开始/结束时间:</span>
                  <span>
                    {{ calcResult.info.startTime || '--' }} -{{ calcResult.info.endTime || '--' }}
                  </span>
                </div>
              </div>
              <div class="form-item">
                <!-- <div class="item-title">
                  <span>计算耗时:</span>
                  <span>{{ calcResult.info.calDur }}</span>
                </div> -->
                <div class="item-title">
                  <span class="title-left">评定结果:</span>
                  <span :class="[calcResult.info.qual == 1 ? 'upass' : 'pass']">
                    {{ calcResult.info.qual == 1 ? '不合格' : '合格' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="view-feature">
            <el-button type="primary" @click="handleViewFeature" size="mini">特征值</el-button>
          </div>
          <div class="echarts-box">
            <SwDispatchChart height="100%" :servers="state.servers" />
            <!-- <morey-chart
              height="100%"
              :x-labels="state.sysTimes"
              :realwater-level="state.rzArr"
              :rain-area="state.rainArr"
              :simulate-water="state.fzArr"
              :real-flow="state.rqArr"
              :simulate-flow="state.fqArr"
              :warn-info="state.warnInfo"
              :fc-time="state.fcTime"
            /> -->
          </div>
        </div>
      </div>
    </div>
    <!-- 场次弹框 -->
    <CountModel ref="countModelRef" :modelObj="props.modelObj" @closeDialog="closeDialog" />
    <!-- 查看计算特征值 -->
    <!-- <el-dialog
      class="el-dialog-box1"
      title="计算特征值"
      v-model="viewFeature"
      width="80%"
      :before-close="dialogBeforeClose"
    >
      <div>
        <el-table
          table-layout="fixed"
          :data="state.eigResult"
          style="width: 100%，height:100%"
          highlight-current-row
          empty-text="暂无数据"
        >
          <el-table-column
            header-align="center"
            align="center"
            prop="leftKey"
            label="项目"
            size="mini"
          ></el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop="floodPeak"
            label="洪峰"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop="floodVolume"
            label="洪量"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop="waterLevel"
            label="水位"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop="flashTime"
            label="洪现时间"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
    </el-dialog> -->
    <appMapInfo ref="mapInfoRef" />
    <!-- 流域弹框 -->
    <basinInfo ref="basinInfoRef" />
    <!-- 河道弹框 -->
    <riverInfo ref="riverInfoRef" />
    <!-- 节点 -->
    <nodeInfo ref="nodeInfoRef" />
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
// import moreyChart from '@/components/app-echart/morey-chart.vue'
//水文
import SwDispatchChart from '@/components/app-echart/sw-dispatch-chart.vue'
import CountModel from '@/pages/ModelManage/cpns/ModelCheck/cpns/CheckPanel/cpns/countModel/index.vue'
import appMapInfo from '@/components/app-map-info/index.vue'
// 引入流域组件
import basinInfo from '@/components/app-basin-river/basin-info/index.vue'
// 引入河道组件
import riverInfo from '@/components/app-basin-river/river-info/index.vue'
// 引入节点组件
import nodeInfo from '@/components/app-basin-river/node-info/index.vue'

// import sectionArr from '@/assets/data/com_data/sec_info.json'
// import cal_result_new from '@/assets/data/com_data/cal_result_new.json'
// import xaj_verify_info from '@/assets/data/com_data/xaj_verify_info.json'
import {
  // 查询新安江场次计算结果
  getXajccResult,
  // 查询时空变源场次计算结果
  getSkbyCcResult,
  // 删除新安江验证方案场次
  deleteXajPlanSession,
  // 删除时空变源场次
  deleteSkbyPlanSession
} from '@/services/modules/model-verify'
import {
  // 新安江验证计算
  xajCalculate,
  // 时空变源验证计算
  skbyCalculate
} from '@/services/modules/model-config.js'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
  showEcharts: {
    type: Boolean,
    default: false
  },
  blkcd: {
    type: String,
    default: ''
  },
  showTabs: {
    type: Boolean,
    default: true
  },
  ccInfo: {
    type: Array,
    default: () => []
  },
  tabsId: {
    type: String,
    default: ''
  },
  modelObj: {
    type: Object,
    default: () => {}
  },
  scid: {
    type: String,
    default: ''
  }
})
// 方案变化 清空图表数据
watch(
  () => {
    props.scid
  },
  () => {
    clearEchart()
    state.servers = []
    calcResult.value.info = {}
  },
  {
    deep: true
  }
)
const sectionArr = ref([])
const countModelRef = ref(null)
// const ccInfos = ref([])
const calcResult = ref({
  info: {}
})
const currentIndex = ref(0)
const currentTime = ref(0)
// 控制计算特征值弹窗
// let viewFeature = ref(false)
const state = reactive({
  servers: [],
  blkcdId: '',
  tabNewData: [],
  evaResult: {},
  tableData: [],
  //时间
  sysTimes: [],
  //降雨量
  rainArr: [],
  //实测流量
  rqArr: [],
  //模拟流量
  fqArr: [],
  //实测水位
  rzArr: [],
  //模拟水位
  fzArr: [],
  // echarts标线数据
  warnInfo: {},
  // 预报时间
  fcTime: '',
  //用于计算的参数
  ccids: '',
  scid: '',
  item: {},
  index: ''
})

function handleAmplify() {
  emit('sendAmplify')
}
const mapInfoRef = ref(null)
const basinInfoRef = ref(null)
const riverInfoRef = ref(null)
const nodeInfoRef = ref(null)
// 打开测试地图弹框
function showMapInfo() {
  mapInfoRef.value.openMapInfo()
}
// 打开流域信息弹框
function showMapbasin() {
  basinInfoRef.value.openMapInfo()
}
// 打开河道信息弹框
function showMapRiver() {
  riverInfoRef.value.openMapInfo()
}
// 打开节点信息弹框
function showMapNode() {
  nodeInfoRef.value.openMapInfo()
}
// 打开计算特征值弹框
function handleViewFeature() {
  // viewFeature.value = true
  emit('computeFeature', calcResult.value.eigResult[0])
}
// 计算
function handleComputed() {
  // 新安江
  if (props.modelObj.typeCode == 'W010002') {
    xajCalculate({ ccids: state.ccids, scid: state.scid }).then((res) => {
      if (res.code == 200) {
        ElMessage.success('计算成功')
        handleClickTime(state.item, state.index)
      }
    })
  } else if (props.modelObj.typeCode == 'W010001') {
    skbyCalculate({ ccids: state.ccids, scid: state.scid }).then((res) => {
      if (res.code == 200) {
        ElMessage.success('计算成功')
        handleClickTime(state.item, state.index)
      }
    })
  }
  // 计算完毕 查看结算结果
}
// 删除验证方案场次
const handleClickDelete = (row) => {
  console.log(row, '场次')
  ElMessageBox.confirm('确认删除此场次?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (props.modelObj.typeCode == 'W010002') {
        // 删除新安江验证方案
        deleteXajPlanSession({ id: row.id }).then((res) => {
          if (res.code == 200) {
            ElMessage.success('删除成功')
            // 删除后重新加载场次列表
            emit('resetCcInfo')
          }
        })
      } else if (props.modelObj.typeCode == 'W010001') {
        // 删除时空变源验证方案
        deleteSkbyPlanSession({ id: row.id }).then((res) => {
          if (res.code == 200) {
            ElMessage.success('删除成功')
            // 删除后重新加载场次列表
            emit('resetCcInfo')
          }
        })
      }
    })
    .catch(() => {})
}
// 新建场次刷新父组件场次列表
const emit = defineEmits(['resetCcInfo', 'sendAmplify', 'computeFeature'])
const closeDialog = () => {
  emit('resetCcInfo')
}

function dateFormat(str) {
  var date = new Date(new Date(str).getTime())
  var Y = date.getFullYear() + '-'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var h = ' ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return Y + M + D + h + m + s
}
function clearEchart() {
  state.sysTimes = []
  state.rainArr = []
  state.rqArr = []
  state.fqArr = []
  state.rzArr = []
  state.fzArr = []
  state.warnInfo = {}
  state.fcTime = ''
}
function handleAddCount() {
  countModelRef.value.handleOpenModal(props.scid)
}
// 点击场次查询计算结果
function handleClickTime(item, index) {
  console.log(item, '验证计算')
  // 保留点击的场次信息 用于计算后使用
  state.item = item
  state.index = index
  // 获取场次方案id集合 用于计算
  state.ccids = item.id
  // 获取验证方案编号 用于计算
  state.scid = item.scid
  clearEchart()
  state.servers = []
  currentTime.value = index
  // 新安江计算
  if (props.modelObj.typeCode == 'W010002') {
    getXajccResult({
      ccid: item.id,
      blkcd: props.blkcd
    }).then((res) => {
      if (res.code === 200) {
        console.log(res.data, '计算结果')
        calcResult.value = res.data
        state.servers = [res.data]
        state.servers = state.servers.map((item) => {
          return { ...item, ...res.data.info, scName: '' }
        })

        // if (res.data[0].result == []) {
        //   state.servers = [];
        //   emitter.emit("clearEcharts");
        // }
        // state.ccBaseInfo = res.data[0].info

        //
        //     eigResult: [
        // //                 floodPeak:洪峰，floodVolume：洪量，waterLevel：水位，FlashTime：洪现时间
        // { leftKey: '模拟', floodPeak: '' },
        // { leftKey: '实测' },
        // { leftKey: '误差' },
        // { leftKey: '许可误差' }
        // ]

        // res.data.eigResult.forEach((val) => {})
        // res.data.ccResult.forEach((v, vIndex) => {
        //   state.sysTimes.push(v.tm)
        //   state.rainArr.push(v.fp)
        //   state.rqArr.push(v.rq)
        //   state.fqArr.push(v.fq)
        //   state.rzArr.push(v.rz)
        //   state.fzArr.push(v.fz)
        // })
        // // 获取标线数据
        // state.warnInfo = res.data.warnInfo
        // state.fcTime = res.data.info.fcTime
      }
    })
  } else if (props.modelObj.typeCode == 'W010001') {
    // 查询时空变源计算结果
    getSkbyCcResult({
      ccid: item.id,
      blkcd: props.blkcd
    }).then((res) => {
      if (res.code === 200) {
        console.log(res.data, '计算结果')
        calcResult.value = res.data
        state.servers = [res.data]
        state.servers = state.servers.map((item) => {
          return { ...item, ...res.data.info, scName: '' }
        })
        // res.data.ccResult.forEach((v, vIndex) => {
        //   state.sysTimes.push(v.tm)
        //   state.rainArr.push(v.fp)
        //   state.rqArr.push(v.rq)
        //   state.fqArr.push(v.fq)
        //   state.rzArr.push(v.rz)
        //   state.fzArr.push(v.fz)
        // })
        // // 获取标线数据
        // state.warnInfo = res.data?.warnInfo
        // state.fcTime = res.data.info.fcTime
      }
    })
  }

  /* let arr = []
  if (props.tabsId) {
    arr = cal_result_new.filter((e) => {
      return e.blkcd === props.tabsId
    })
  } else {
    arr = cal_result_new.filter((e) => {
      return e.blkcd === state.blkcdId
    })
  }
  state.evaResult = arr[0].evaResult.filter((child) => {
    return child.code === item.code
  })
  state.tableData = state.evaResult
  if (item) {
    state.forecastResult = arr[0].forecastResult.filter((i) => {
      return i.ccCode === item.code
    })
    state.forecastResult[0]?.resultData.forEach((v, vIndex) => {
      state.sysTimes.push(v.tm)
      state.rainArr.push(v.p)
      state.rqArr.push(v.rq)
      state.fqArr.push(v.fq)
      state.rzArr.push(v.rz)
      state.fzArr.push(v.fz)
    })
  } */
}
// function handleClickTabs(item, index) {
//   state.blkcdId = item.blkcd ? item.blkcd : ''
//   currentIndex.value = index
//   // state.tabNewData = xaj_verify_info.filter((e) => {
//   //   return item.blkcd === e.blkcd
//   // })
//   // ccInfos.value = state.tabNewData[0]?.verifySchemes[0].ccInfo

//   // handleClickTime(ccInfos.value[0], 0)
// }
watch(
  () => props.tabsId,
  () => {
    if (props.ccInfo[0]) {
      handleClickTime(props.ccInfo[0], 0)
    } else {
      // handleClickTabs(sectionArr[0], 0)
      // handleClickTime(ccInfos.value[0], 0)
      // 清空计算结果
      if (state.eigResult?.length) {
        state.eigResult.forEach((e) => {
          e.flashTime = ''
          e.floodPeak = ''
          e.floodVolume = ''
          e.waterLevel = ''
        })
      }

      calcResult.value.info = {}
    }
  }
)
watch(
  () => props.ccInfo,
  () => {
    if (props.ccInfo[0]) {
      handleClickTime(props.ccInfo[0], 0)
    } else {
      // handleClickTabs(sectionArr[0], 0)
      // handleClickTime(ccInfos.value[0], 0)
    }
  }
)
onMounted(() => {
  if (props.ccInfo[0]) {
    handleClickTime(props.ccInfo[0], 0)
  } else {
    console.log('xxxxxxx')
    // handleClickTabs(sectionArr[0], 0)
    // handleClickTime(ccInfos.value[0], 0)
  }
})
</script>
<style lang="less" scoped>
.title-left {
  color: #797979;
}
.font-blue {
  color: #409eff;
}
.comput-result {
  width: 100%;
  font-size: 14px;
  height: 100%;
  :deep(.el-dialog-box1) {
    height: 60vh;
    margin-top: 5vh !important;
    .el-dialog__body {
      height: calc(100% - 100px);
    }
  }
  .result-box {
    width: 100%;
    height: 100%;
    display: flex;
    .tabs-box {
      width: 120px;
      height: 100%;
      margin-right: 15px;
      .tabs-title {
        height: 30px;
        background: #f2f2f2;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        span {
          font-weight: 600;
        }
      }
      .tabs-list {
        height: calc(100% - 30px);
        background: #d7d4d427;
        overflow-y: auto;
        .list-item {
          width: 100%;
          height: 25px;
          text-align: center;
          cursor: pointer;
          &.active {
            span {
              color: #0154db;
            }
          }
          span {
            width: 100%;
            color: black;
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .list-item:hover {
          width: 100%;
          height: 25px;
          cursor: pointer;
          span {
            color: #0154db;
          }
        }
      }
    }
    .box-right {
      flex: 1;
      width: calc(100% - 135px);
      height: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      .comput-times {
        width: 100%;
        height: 70px;
        .times-title {
          // line-height: 40px;
          height: 40px;
          position: relative;

          .add-count {
            position: absolute;
            right: 200px;
          }
          .comput {
            position: absolute;
            right: 100px;
          }
          .btn-plus {
            position: absolute;
            margin-top: 0;
            right: 15px;
            font-size: 25px;
            font-weight: bold;
          }
        }
        .times-list {
          // display: -webkit-box;
          display: flex;
          width: 100%;
          height: 40px;
          overflow-x: auto;
          white-space: nowrap;
          // white-space: wrap;
          // span {
          //   width: 100%;
          //   text-align: center;
          // }
          .times-item {
            flex-shrink: 0;
            width: 150px;
            height: 30px;
            border: 1px solid gray;
            border-radius: 8px;
            display: flex;
            // justify-content: center;
            justify-content: space-between;
            align-items: center;
            margin-right: 10px;
            padding: 0 10px;
            cursor: pointer;
            .close-icon {
              color: red !important;
            }
            &.active {
              span {
                color: #0154db;
              }
            }
            &:hover {
              color: #0154db;
            }
            span {
              color: gray;
            }
          }
        }
        .times-center {
        }
      }
      .switch-box {
        width: 100%;
        height: calc(100% - 70px);
        .comput-result-box {
          width: 100%;
          .box-title {
            height: 30px;
            padding-top: 10px;
          }
          .box-form {
            .form-item {
              display: flex;
              justify-content: space-between;
              // flex-wrap: wrap;
              // width: 100%;
              margin-left: 5px;
              .pass {
                color: #78ba1c;
              }
              .upass {
                color: orange;
              }
              .item-title {
                // flex: 0.25;
                margin-right: 20px;
                height: 30px;
                &:nth-of-type(1) {
                  width: 35%;
                }
                span:nth-of-type(1) {
                  margin-right: 10px;
                }
                span:nth-of-type(2) {
                  font-weight: 600;
                }
              }
            }
          }
        }
        .computed-table {
          width: 100%;
          // height: 80px;
          overflow-x: auto;
        }
        .view-feature {
          display: flex;
          height: 50px;
          justify-content: flex-end;
        }
        .echarts-box {
          width: 100%;
          // height: calc(100% - 170px);
          height: 400px;
          padding: 5px;
        }
      }
    }
  }
}
</style>
